const mongoose = require("mongoose");

const RoleSchema = new mongoose.Schema(
  {
    name: {
      type: String,
    },
    resource: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "resource",
        }
    ]
  },
  {
    timestamps: true, // 这将自动添加 createdAt 和 updatedAt 字段
  }
);

RoleSchema.virtual("formattedCreatedAt").get(function () {
  return this.createdAt.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
});


RoleSchema.statics.paginate = async function (filter = {}, options = {}) {
  const { limit = 10, page = 1 } = options;
  const skip = (page - 1) * limit;
  const count = await this.countDocuments(filter);
  const entity = await this.find(filter)
    .limit(limit)
    .skip(skip)
    .sort({ createdAt: -1 })

  return {
    results: entity.map((item) => {
      return {
        ...item.toObject(),
        formattedCreatedAt: item.formattedCreatedAt
     } 
    }),
    count,
    page,
    limit,
  };
};


module.exports = mongoose.model("role", RoleSchema);
